import {
  ref,
  computed,
  onMounted,
  watch,
  Ref,
  SetupContext
} from 'vue'
import { _anyPost, _getCurrentInstance, _isValidValue } from '@/utils';
import { TableProps, TableEmits } from './table';

export const useTable = (
  props: TableProps,
  targetRef: Ref<HTMLElement | undefined>
) => {
  yLog.flow('useTable', props, targetRef);

  /* ****** 内部参数定义 ****** */
  const 
    instance = _getCurrentInstance(),
    emit = instance.emit as SetupContext<TableEmits>['emit'],
    slots = instance.slots as SetupContext['slots'],
    isRemote = _isValidValue(props.link.url),
    show = ref(false),
    data = ref<yAny>([]);

  /* ****** computed定义 ****** */
  // 判断操作按钮行是否显示
  // const isShowOperatorRow = computed(() => {
  //   return props.leftBtns.length > 0 || Object.keys(slots).length > 0;
  // });

  /* ****** 内部函数方法定义 ****** */
  // 加载数据
  async function loadTableData() {
    let result = [];
    const res = await _anyPost(props.link);
    yLog.info('_anyPost', res);
    if (res.errorCode === 0) {
      result = res.data;
    } else {
      // todo 待优化  可增加弹窗提示等
      console.error('[error]', res);
    }
    return result;
  }

  async function initData() {
    // data.value = isRemote ? await loadTableData() : props.tableData;
  }


  const handleOperatorBtnClick = (action: string) => {
    // emit('btnClick', action)
    yLog.info(action);
    // show.value = true;
    // action === 'refresh' ? emit('btnClick', action) : yLog.info(data.value, props.tableData);
    action === 'refresh' && loadTableData();
  }

  /* ****** 响应api处理 ****** */
  // watch(() => props.tableData, (value) => { 
  //   yLog.info('watch', value);
  //   data.value = value;
  // });
  /* ****** 生命周期钩子 ****** */
  onMounted(()=>{
    initData();
  })
  return {
    show,
    data,
    // isShowOperatorRow,
    handleOperatorBtnClick,
  };
}